import { getCommentApi, likeCommentApi, sendCommentApi, sendCommentData, unlikeCommentApi } from '@/api/comment';
import store, { AppDispatch } from '..';
import { Toast } from 'antd-mobile';
import { commentItem } from '../reducer/comment';

export const getCommentByIdAction = (id: string, type: 'a' | 'c', last_id?: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentApi(id, type, last_id);
    dispatch({ type: 'comment/setCommentData', payload: res.data });
  };
};
//清除评论数据
export const clearCommentDataAction = () => ({
  type: 'comment/clearCommentData',
});

//回复弹窗存储原始数据
export const setReplyOriginDataAction = (payload: any) => ({
  type: 'comment/setReplyOriginData',
  payload,
});
//获取回复评论的数据
export const getReplyCommentAction = (id: string, type: 'a' | 'c') => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentApi(id, type);
    dispatch({ type: 'comment/setReplyCommentData', payload: res.data });
  };
};
//清除回复评论的数据
export const cleatReplyCommentAction = () => ({
  type: 'comment/setReplyCommentData',
  payload: {},
});

//发送文章评论
export const sendCommentAction = (data: sendCommentData) => {
  return async (dispatch: AppDispatch) => {
    const res = await sendCommentApi(data);
    //新发送的评论追加到评论列表中
    dispatch({ type: 'comment/appendAddCommentData', payload: res.data.new_obj });
  };
};
//发送回复评论
export const sendCommentToCommentAction = (data: sendCommentData) => {
  return async () => {
    await sendCommentApi(data);
  };
};

//对评论点赞
export const likeCommentAction = (id: string) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const commentList = getState().comment.commentData.results || [];
    const commentItem = commentList.find((item: commentItem) => item.com_id === id);
    //判断是否已经点赞
    if (commentItem?.is_liking) {
      //取消对评论点赞
      await unlikeCommentApi(id);
    } else {
      //对评论点赞
      await likeCommentApi(id);
    }
    //点赞成功，将点赞的评论id存储到点赞列表中
    dispatch({ type: 'comment/likeComment', payload: id });
    Toast.show({ content: commentItem?.is_liking ? '点赞成功' : '取消点赞' });
  };
};
